﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Configuration;

namespace YourWorldServer
{
    class Program
    {
        private static readonly string ConfigurationFileName = "ServerConfigFile.config";
        private static readonly string WebServicesLocationKey = "WebServicesLocation";

        private static string webServicesLocation;

        static void Main( string[] args )
        {
            Initialize();

            SocketServer socketServer = null;
            PolicyServer policyServer = null;

            try
            {
                Console.WriteLine( "Starting policy server" );
                policyServer = new PolicyServer();
                policyServer.StartPolicyServer();
                Console.WriteLine( "Policy server successfully started" );

                socketServer = new SocketServer( webServicesLocation );

                socketServer.StartSocketServer();

                Console.WriteLine( "Press any key to exit the server" );
                Console.ReadLine();

                policyServer.StopPolicyServer();
                socketServer.StopSocketServer();
            }
            catch ( Exception e )
            {
                if ( policyServer != null )
                    policyServer.StopPolicyServer();

                if ( socketServer != null )
                    socketServer.StopSocketServer();
            }
        }

        static void Initialize()
        {
            string path = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location );
            string configFile = path + @"\" + ConfigurationFileName;

            ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
            configFileMap.ExeConfigFilename = configFile;

            Configuration config = null;
            try
            {
                config = ConfigurationManager.OpenMappedExeConfiguration( configFileMap, ConfigurationUserLevel.None );
                
                string[] keys = config.AppSettings.Settings.AllKeys;
                webServicesLocation = config.AppSettings.Settings[WebServicesLocationKey].Value;
            }
            catch ( Exception e )
            {
                Console.WriteLine( "Inicialization from the configuration file has failed. Please review the configuratin file." );

                Console.WriteLine( "Error details:" );
                Console.WriteLine( e.ToString() );
            }
        }
    }
}
